<template>
  <van-nav-bar :title="title" left-arrow @click-left="onClickLeft">
    <template #right>
      <van-icon @click="onSearch" name="search" v-if="nav === 1" size="20" />
      <van-icon
        @click="showPopover++"
        name="setting-o"
        v-if="nav === 2"
        size="20"
      />
      <van-icon @click="onMessage" name="more-o" v-if="nav === 3" size="20" />
    </template>
  </van-nav-bar>
  <div id="content">
    <router-view
      v-if="isRouterAlive"
      v-bind="nav === 2 ? { showNavByLay: showPopover } : {}"
    />
  </div>
  <van-tabbar v-if="nav !== 5" route>
    <van-tabbar-item to="/" icon="home-o" name="index">首页</van-tabbar-item>
    <van-tabbar-item to="/friends" icon="friends-o" name="friend"
      >联系人</van-tabbar-item
    >
    <van-tabbar-item to="/team" icon="apps-o" name="team">队伍</van-tabbar-item>
    <van-tabbar-item to="/user" icon="manager-o" name="user"
      >我的</van-tabbar-item
    >
  </van-tabbar>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { ref, nextTick, provide } from "vue";
import routes from "../config/route";

const isRouterAlive = ref(true); // 局部组件刷新
const reload = () => {
  isRouterAlive.value = false;
  nextTick(() => {
    isRouterAlive.value = true;
  });
};
provide("reload", reload); //将刷新的函数上传引共全局引用

// 根据路由展示右上角图标、切换标题、
const router = useRouter();
const nav = ref(0); //右上角图标类型
const showPopover = ref(0); //控制个人页面的动作面板展示
const DEFAULT_TITLE = "篝火"; //默认名字
const title = ref(DEFAULT_TITLE); //动态名字
router.beforeEach((to) => {
  const toPath = to.path;
  if (toPath === "/") nav.value = 1;
  else if (toPath === "/user") nav.value = 2;
  else if (toPath === "/friends") nav.value = 3;
  else if (toPath === "/message") nav.value = 4;
  else if (toPath === "/user/login") nav.value = 5;
  else nav.value = 0;

  const route = routes.find((route) => {
    return toPath == route.path;
  });
  title.value = route?.title ?? DEFAULT_TITLE;
});

const onClickLeft = () => {
  router.back();
};

const onSearch = () => {
  router.push("/search");
};

const onMessage = () => {
  router.push("/message");
};
</script>

<style scoped>
#content {
  padding-bottom: 3.125rem;
}
</style>
